package com.wsc.controller;

import com.wsc.pojo.User;
import com.wsc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@Controller
public class MyController {

    @Autowired
    UserService userService;

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello Shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "/user/add";
    }

    @RequestMapping("/user/update")
    public String update(){
        return "/user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            return "index";
        }catch (UnknownAccountException uae){
            model.addAttribute("msg", "用户名错误或者密码错误");
            return "login";
        }catch (IncorrectCredentialsException ice){
            model.addAttribute("msg", "用户名错误或者密码错误");
            return "login";
        }
    }

    /**
     * shiro 使用注解配置权限
     * @return
     */
    @RequiresPermissions("visitor:check")
    @RequestMapping("/getuser")
    @ResponseBody
    public List<User> getUser(){
        return userService.getAll();
    }

    /**
     * 没有权限的返回值
     * @return
     */
    @RequestMapping("/noauth")
    @ResponseBody
    public String noauth(){
        return "当前用户没有权限";
    }

}
